<template>
  <el-form ref="formRef" :model="modelData" :rules="rules" label-width="120px" class="mt-20px">
    <el-form-item label="流程Keyy" prop="key" class="mb-20px">
      <div class="flex items-center">
        <el-input
          class="!w-440px"
          v-model="modelData.key"
          :disabled="!!modelData.id"
          placeholder="请输入流程Key例如leaveProcess"
        />
        <el-tooltip
          class="item"
          :content="modelData.id ? '流程Key不可修改' : '新建后，流程标识不可修改'"
          effect="light"
          placement="top"
        >
          <el-icon><QuestionFilled /></el-icon>
          
        </el-tooltip>
      </div>
    </el-form-item>
    <el-form-item label="流程名称" prop="name" class="mb-20px">
      <el-input
        v-model="modelData.name"
        :disabled="!!modelData.id"
        clearable
        placeholder="请输入流程名称"
      />
    </el-form-item>
    <el-form-item label="流程分类" prop="category" class="mb-20px">
      <el-select
        class="!w-full"
        v-model="modelData.category"
        clearable
        placeholder="请选择流程分类"
      >
        <el-option
          v-for="category in categoryList"
          :key="category.modelCategory"
          :label="category.name"
          :value="category.modelCategory"
        />
      </el-select>
    </el-form-item>

    <el-form-item label="流程描述" prop="description" class="mb-20px">
      <el-input v-model="modelData.description" clearable type="textarea" />
    </el-form-item>
    <el-form-item label="流程类型" prop="modelType" class="mb-20px">
      <el-radio-group v-model="modelData.modelType">
        <el-radio
          v-for="option in bpmnModelTypeOptions"
          :key="option.value"
          :value="option.value"
        >
          {{ option.label }}
        </el-radio>
      </el-radio-group>
    </el-form-item>

    <el-form-item label="谁可以发起" prop="startUserType" class="mb-20px">
      <el-select
        v-model="modelData.startUserType"
        placeholder="请选择谁可以发起"
        @change="handleStartUserTypeChange"
      >
        <el-option label="全员" :value="0" />
        <el-option label="指定人员" :value="1" />
        <el-option label="指定部门" :value="2" />
      </el-select>
      <div v-if="modelData.startUserType === 1" class="mt-2 flex flex-wrap gap-2">


       <div class="flex h-32px rounded-3xl basis-full" ><el-button type="primary" link @click="openStartUserSelect">
          <el-icon ><Plus /></el-icon>选择人员
        </el-button>
      </div>

        <div
          v-for="user in selectedStartUsers"
          :key="user.userId"
          class="flex"
        >

           <div class="flex items-center">
                <el-tag
                  class="mx-1"
                  closable
                  type="success"
                  size="large"
                  @close="handleRemoveStartUser(user)"
                >
                  {{ user.avatar }}{{ user.nickName }}
                </el-tag>
            </div>

          
        </div>

      </div>
      <div v-if="modelData.startUserType === 2" class="mt-2 flex flex-wrap gap-2">

       <div class="flex h-32px rounded-3xl basis-full" ><el-button type="primary" link @click="openStartDeptSelect">
          <el-icon ><Plus /></el-icon>选择部门
        </el-button>
      </div>


        <div
          v-for="dept in selectedStartDepts"
          :key="dept.deptId"
          class=""
        >

          <div class="flex items-center">
                <el-tag
                  class="mx-1"
                  closable
                  type="success"
                  size="large"
                  @close="handleRemoveStartDept(dept)"
                >
                <el-icon><OfficeBuilding /></el-icon>
                  {{ dept.deptName }}
                </el-tag>
            </div>


        </div>

      </div>
    </el-form-item>
    <el-form-item label="流程管理员" prop="managerUserIdList" class="mb-20px">
      <div class="flex h-32px rounded-3xl basis-full" ><el-button type="primary" link @click="openManagerUserSelect">
          <el-icon><Plus /></el-icon>选择人员
        </el-button>
      </div>
        <div
          v-for="user in selectedManagerUsers"
          :key="user.userId"
          class="flex "
        >

        <!-- 将昵称和删除图标放在一个容器内，并设置flex布局 -->
            <div class="flex items-center">
                <el-tag
                  class="mx-1"
                  closable
                  type="success"
                  size="large"
                  @close="handleRemoveManagerUser(user)"
                >
                  {{ user.avatar }}{{ user.nickName }}
                </el-tag>
            </div>

        </div>
        
      
    </el-form-item>
  </el-form>

  <!-- 用户选择弹窗 -->
  <UserSelectForm ref="userSelectFormRef" @confirm="handleUserSelectConfirm" />
  <!-- 部门选择弹窗 -->
  <DeptSelectForm
    ref="deptSelectFormRef"
    :multiple="true"
    :check-strictly="true"
    @confirm="handleDeptSelectConfirm"
  />
</template>

<script lang="ts" setup>
import { UserSimpleVO,DeptSimpleVO } from '@/api/workflow/bpmnModel.ts'
import { BpmnCategory } from '@/api/workflow/bpmnCategory.ts'
import UserSelectForm from '@/components/UserSelectForm/index.vue'
import DeptSelectForm from '@/components/DeptSelectForm/index.vue'
import { BpmnOption } from '@/store/dataType'
import useBpmnEnumStore from '@/store/bpmnStore'
const bpmnStore = useBpmnEnumStore()

//传递给组件props
const props = defineProps({
  categoryList: {
    type: Array as PropType<BpmnCategory[]>,
    required: true
  },
  userList: {
    type: Array as PropType<UserSimpleVO[]>,
    required: true
  },
  deptList: {
    type: Array as PropType<DeptSimpleVO[]>,
    required: true
  }
})


//挂载时加载流程模型数据
const bpmnModelTypeOptions = ref<BpmnOption[]>([])
onBeforeMount(


  async () => {
  if(!bpmnStore.isInitialized){
    await bpmnStore.init();
  }
  bpmnModelTypeOptions.value = bpmnStore.getBpmnModelTypeOptions
  //console.log('基本信息bpmnModelTypeOptions.value',bpmnModelTypeOptions.value)


})


const formRef = ref()
const selectedStartUsers = ref<UserSimpleVO[]>([])
const selectedStartDepts = ref<DeptSimpleVO[]>([])
const selectedManagerUsers = ref<UserSimpleVO[]>([])
const userSelectFormRef = ref()
const deptSelectFormRef = ref()
const currentSelectType = ref<'start' | 'manager'>('start')

const rules = {
  name: [{ required: true, message: '流程名称不能为空', trigger: 'blur' }],
  key: [
    { required: true, message: '流程标识不能为空', trigger: 'blur' },
    {
      validator: (_rule: any, value: string, callback: any) => {
        if (!value) {
          callback()
          return
        }
        if (!/^[a-zA-Z_][\-_.0-9_a-zA-Z$]*$/.test(value)) {
          callback(new Error('只能包含字母、数字、下划线、连字符和点号，且必须以字母或下划线开头'))
          return
        }
        callback()
      },
      trigger: 'blur'
    }
  ],
  category: [{ required: true, message: '流程分类不能为空', trigger: 'blur' }],
  modelType: [{ required: true, message: '流程设计器类型不能为空', trigger: 'blur' }],
  // visible: [{ required: true, message: '是否可见不能为空', trigger: 'blur' }],
  managerUserIdList: [{ required: true, message: '流程管理员不能为空', trigger: 'blur' }]
}

// 创建本地数据副本
const modelData = defineModel<any>()

// 初始化选中的用户
watch(
  () => modelData.value,
  (newVal) => {
    if (newVal.startUserIdList?.length) {
      selectedStartUsers.value = props.userList.filter((user: UserSimpleVO) =>
        newVal.startUserIdList.includes(user.userId)
      ) as UserSimpleVO[]
    } else {
      selectedStartUsers.value = []
    }
    if (newVal.startDeptIdList?.length) {
      selectedStartDepts.value = props.deptList.filter((dept: DeptSimpleVO) =>
      //看看传递过来的如果是已创建的模型，就deptList是所有部门的数据，进行匹配
        newVal.startDeptIdList.includes(dept.deptId)
      ) as DeptSimpleVO[]
    } else {
      selectedStartDepts.value = []
    }
    if (newVal.managerUserIdList?.length) {
      selectedManagerUsers.value = props.userList.filter((user: UserSimpleVO) =>
        newVal.managerUserIdList.includes(user.userId)
      ) as UserSimpleVO[]
    } else {
      selectedManagerUsers.value = []
    }
  },
  {
    immediate: true
  }
)

/** 打开发起人选择 */
const openStartUserSelect = () => {
  currentSelectType.value = 'start'
  userSelectFormRef.value.open(0, selectedStartUsers.value)
}

/** 打开部门选择 */
const openStartDeptSelect = () => {
  deptSelectFormRef.value.open(selectedStartDepts.value)
}

/** 打开管理员选择 */
const openManagerUserSelect = () => {
  currentSelectType.value = 'manager'
  userSelectFormRef.value.open(0, selectedManagerUsers.value)
}

/** 处理用户选择确认，第一个参数只是从子组件emit接收过来的无需处理
 * 第二个参数接收过来的是USER数组
 */
const handleUserSelectConfirm = (activityId,users: UserSimpleVO[]) => {
  if (currentSelectType.value === 'start') {
    modelData.value = {
      ...modelData.value,
      startUserIdList: users.map((u) => u.userId)
    }
  } else {
    modelData.value = {
      ...modelData.value,
      managerUserIdList: users.map((u) => u.userId)
    }
  }
}

/** 处理部门选择确认,第二个参数接收过来的是选择的节点对象数组，所以直接取id */
const handleDeptSelectConfirm = (deptList:any[]) => {

  modelData.value = {
    ...modelData.value,
    startDeptIdList: deptList.map((node) => node.id)
  }
  console.log('发起部门的配置人员',selectedStartDepts.value)
}





/** 处理发起人类型变化 */
const handleStartUserTypeChange = (value: number) => {
  if (value === 0) {
    modelData.value = {
      ...modelData.value,
      startUserIdList: [],
      startDeptIdList: []
    }
  } else if (value === 1) {
    modelData.value = {
      ...modelData.value,
      startDeptIdList: []
    }
  } else if (value === 2) {
    modelData.value = {
      ...modelData.value,
      startUserIdList: []
    }
  }
}

/** 移除发起人 */
const handleRemoveStartUser = (user: UserSimpleVO) => {
  modelData.value = {
    ...modelData.value,
    startUserIdList: modelData.value.startUserIdList.filter((id: number) => id !== user.userId)
  }
}

/** 移除部门 */
const handleRemoveStartDept = (dept: DeptSimpleVO) => {
  modelData.value = {
    ...modelData.value,
    startDeptIdList: modelData.value.startDeptIdList.filter((id: number) => id !== dept.deptId)
  }
}

/** 移除管理员 */
const handleRemoveManagerUser = (user: UserSimpleVO) => {
  modelData.value = {
    ...modelData.value,
    managerUserIdList: modelData.value.managerUserIdList.filter((id: number) => id !== user.userId)
  }
}

/** 表单校验 */
const validate = async () => {
  await formRef.value?.validate()
}

defineExpose({
  validate
})
</script>

<style lang="scss" scoped>
.bg-gray-100 {
  background-color: #f5f7fa;
  transition: all 0.3s;

  &:hover {
    background-color: #e6e8eb;
  }

  .ep-close {
    font-size: 14px;
    color: #909399;
    transition: color 0.3s;

    &:hover {
      color: #f56c6c;
    }
  }

  
}


</style>
